﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Effects;
using System.Windows.Shapes;
using ArmoryData;
using ArmoryData.Character;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Taskbar;

namespace ArmoryViewer.Windows
{
    /// <summary>
    /// Interaction logic for ProfileWindow.xaml
    /// </summary>
    public partial class ProfileWindow : GlassWindow
    {
        public CharacterInfo Character { get; set; }
        public ProfileWindow()
        {
            InitializeComponent();
        }

        private void ProfileWindow_Loaded(object sender, RoutedEventArgs e)
        {
            grdNoGlass.Background = SystemColors.ControlBrush;

            AeroGlassCompositionChanged += new AeroGlassCompositionChangedEvent(MainWindow_AeroGlassCompositionChanged);
            if (App.IsVista && AeroGlassCompositionEnabled)
            {
                SetAeroGlassTransparency();
            }
            else
            {
                this.Background = SystemColors.ControlBrush;
            }
            SetBlurs();
        }

        public void DisplayData()
        {
            String portraitDir;
            if (Character.Level >= 0 && Character.Level <= 59)
            {
                portraitDir = "wow-default";
            }
            else if (Character.Level >= 60 && Character.Level <= 69)
            {
                portraitDir = "wow";
            }
            else if (Character.Level >= 70 && Character.Level <= 79)
            {
                portraitDir = "wow-70";
            }
            else if (Character.Level >= 80)
            {
                portraitDir = "wow-80";
            }
            else
            {
                portraitDir = "wow-default";
            }
            string url = "http://www.wowarmory.com/_images/portraits/" + portraitDir + "/" + (int)Character.Gender + "-" + (int)Character.Race + "-" + (int)Character.Class + ".gif";
            imgPortrait.Source = LoadImage(new Uri(url));

            lblName.Text = Character.Prefix + Character.Name + Character.Suffix;
            lblGuild.Text = Character.GuildName;
            lblInfo.Text = String.Format("Level {0} {1} {2} {3}", Character.Level, Character.Gender, Character.Race, Regex.Replace(Character.Class.ToString(), "([a-z])([A-Z])", "$1 $2"));
            lblRealm.Text = Character.Realm;
            lblBattlegroup.Text = Character.BattleGroup;
            lblAchievementPoints.Text = Character.Points.ToString();
            picCrest.Source = LoadImage(new Uri(
                string.Format("/ArmoryViewer;component/Resources/{0}.gif",
                Character.Faction.ToString().ToLower()),
                UriKind.Relative));

            LoadCharacterTab();
        }

        void LoadCharacterTab()
        {
            // Items
            SetItemData(ref imgItem1, Character.Items[0]);
            SetItemData(ref imgItem2, Character.Items[1]);
            SetItemData(ref imgItem3, Character.Items[2]);
            SetItemData(ref imgItem4, Character.Items[14]);
            SetItemData(ref imgItem5, Character.Items[4]);
            SetItemData(ref imgItem6, Character.Items[3]);
            SetItemData(ref imgItem7, Character.Items[18]);
            SetItemData(ref imgItem8, Character.Items[8]);
            SetItemData(ref imgItem9, Character.Items[9]);
            SetItemData(ref imgItem10, Character.Items[5]);
            SetItemData(ref imgItem11, Character.Items[6]);
            SetItemData(ref imgItem12, Character.Items[7]);
            SetItemData(ref imgItem13, Character.Items[10]);
            SetItemData(ref imgItem14, Character.Items[11]);
            SetItemData(ref imgItem15, Character.Items[12]);
            SetItemData(ref imgItem16, Character.Items[13]);
            SetItemData(ref imgItem17, Character.Items[15]);
            SetItemData(ref imgItem18, Character.Items[16]);
            SetItemData(ref imgItem19, Character.Items[17]);

            // Talent Spec
            cboSpecs.Items.Clear();
            int active = 0, count = 0;
            foreach (TalentSpec spec in Character.TalentSpecs)
            {
                if (spec.Id == -1) cboSpecs.Items.Add("No Spec");
                else cboSpecs.Items.Add(spec.ToString());
                if (spec.Active) active = count;
                count++;
            }
            cboSpecs.SelectedIndex = active;

            //Professions
            if (Character.Professions[0].Name != null)
            {
                lblProf1.Text = Character.Professions[0].Name;
                lblProf1Val.Text = Character.Professions[0].Value + " / " + Character.Professions[0].Max;
                try { pgsProf1.Value = Convert.ToInt32(((float)Character.Professions[0].Value / (float)Character.Professions[0].Max) * 100); }
                catch { pgsProf1.Value = 100; }
            }
            else
            {
                lblProf1.Text = "None";
                lblProf1Val.Text = "N/A";
                pgsProf1.Value = 0;
            }
            imgProf1.Source = LoadImage(new Uri("http://www.wowarmory.com/_images/icons/professions/" + lblProf1.Text.ToLower() + "-sm.gif"));

            if (Character.Professions[1].Name != null)
            {
                lblProf2.Text = Character.Professions[1].Name;
                lblProf2Val.Text = Character.Professions[1].Value + " / " + Character.Professions[1].Max;
                try { pgsProf2.Value = Convert.ToInt32(((float)Character.Professions[1].Value / (float)Character.Professions[1].Max) * 100); }
                catch { pgsProf2.Value = 100; }
            }
            else
            {
                lblProf2.Text = "None";
                lblProf2Val.Text = "N/A";
                pgsProf2.Value = 0;
            }
            imgProf2.Source = LoadImage(new Uri("http://www.wowarmory.com/_images/icons/professions/" + lblProf2.Text.ToLower() + "-sm.gif"));

            // Health / Energy
            lblHealthVal.Text = Character.CharacterBars.Health.Effective.ToString();
            CharacterBar energyBar = Character.CharacterBars.SecondBar;
            lblEnergy.Text = energyBar.Type.ToString();
            lblEnergyLevel.Text = energyBar.Effective.ToString();
            picEnergy.Source = LoadImage(new Uri(
                string.Format("/ArmoryViewer;component/Resources/bar-{0}.gif", 
                energyBar.Type.ToString().ToLower()), 
                UriKind.Relative));
        }

        void SetItemData(ref Image itemBox, Item item, bool ignoreImage=false)
        {
            const String ITEM_PIC_FORMAT = "http://wowarmory.com/wow-icons/_images/51x51/{0}.jpg";
            if (!ignoreImage) itemBox.Source = LoadImage(new Uri(string.Format(ITEM_PIC_FORMAT, item.Icon)));
            Color qColor = Colors.Black;
            switch (item.Quality)
            {
                case 0: qColor = Colors.Gray; break;       //Vendor Trash
                case 1: qColor = Colors.Black; break;    //Normal
                case 2: qColor = Colors.LightGreen; break;    //Uncommon
                case 3: qColor = Colors.Blue; break;       //Rare
                case 4: qColor = Colors.DarkViolet; break;   //Epic
                case 5: qColor = Colors.Orange; break;  //Legendary
                case 6: qColor = Colors.Red; break;        //Artifact (Account Bound in WotLK)
                default: qColor = Colors.Black; break;  //Unknown
            }
            itemBox.Effect = CreateBlur(qColor, 8, 2);
            itemBox.Tag = item.Slot;
        }

        DropShadowEffect CreateBlur(Color color, double radius, double depth)
        {
            return new DropShadowEffect()
            {
                BlurRadius = radius,
                Color = color,
                ShadowDepth = depth,
            };
        }

        ImageSource LoadImage(Uri imageUri)
        {
            return new BitmapImage(imageUri);
        }

        void MainWindow_AeroGlassCompositionChanged(object sender, AeroGlassCompositionChangedEvenArgs e)
        {
            if (App.IsVista && e.GlassAvailable)
            {
                SetAeroGlassTransparency();
                InvalidateVisual();
                ExcludeElementFromAeroGlass(grdNoGlass);
            }
            else
                this.Background = SystemColors.ControlBrush;
            SetBlurs();
        }

        void SetBlurs()
        {
            DropShadowEffect effect;
            if (App.IsVista && AeroGlassCompositionEnabled)
            {
                effect = new DropShadowEffect()
                {
                    ShadowDepth = 0,
                    BlurRadius = 6,
                    Color = Colors.White,
                    RenderingBias = RenderingBias.Quality
                };
            }
            else effect = null;

            lblRealm.Effect =
                lblBattlegroup.Effect =
                lblAchievementPoints.Effect =
                lblName.Effect =
                lblGuild.Effect =
                lblInfo.Effect =
                effect;
        }

        private void cboSpecs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int specId = cboSpecs.SelectedIndex;
            TalentSpec spec;

            if (specId == -1) return;
            try
            {
                spec = Character.TalentSpecs[specId];

            }
            catch { return; }

            int[] talentPoints = { spec.TreeOne, spec.TreeTwo, spec.TreeThree };
            lblSpec.Text = "";

            const string SPEC_IMG_FORMAT = "http://www.wowarmory.com/_images/icons/class/{0}/talents/{1}.gif";
            if (spec.Name == "No Spec") imgSpec.Source = LoadImage(new Uri("http://www.wowarmory.com/_images/icons/class/talents/untalented.gif"));
            else imgSpec.Source = LoadImage(new Uri(string.Format(SPEC_IMG_FORMAT, (int)Character.Class, spec.Id)));
            
            //string s = spec.Name;
            //if (s == "Feral Combat" || s == "Retribution" || s == "Assasination" || s == "Combat" || s == "Subtlety" || s == "Enhancement" || s == "Arms" || s == "Fury" || s == "Blood" || (s == "Frost" && character.classId == 6) || s == "Unholy")
            //{
            //    cboStats2.SelectedIndex = 1;
            //}
            //else if (s == "Balance" || s == "Restoration" || s == "Arcane" || s == "Fire" || s == "Frost" || s == "Holy" || s == "Discipline" || s == "Shadow" || s == "Elemental" || s == "Affliction" || s == "Demonology" || s == "Destruction")
            //{
            //    cboStats2.SelectedIndex = 3;
            //}
            //else if (s == "Beast Mastery" || s == "Marksmanship" || s == "Survival")
            //{
            //    cboStats2.SelectedIndex = 2;
            //}
            //else if (s == "Protection")
            //{
            //    cboStats2.SelectedIndex = 4;
            //}
            //else
            //{
            //    cboStats2.SelectedIndex = 1;
            //}
            //cboStats_SelectedIndexChanged(cboStats1, new EventArgs());
        }

        ArmoryViewer.Controls.ItemTooltip itemTtp;
        Image blurredImage;

        void DisableItemTooltip()
        {
            if (itemTtp == null) return;
            pnlMid.Children.Clear();
            foreach (UIElement e in itemTtp.Replacing)
            {
                pnlMid.Children.Add(e);
            }
            itemTtp = null;
            SetItemData(ref blurredImage, Character.Items[int.Parse(blurredImage.Tag.ToString())], true);
        }

        bool tooltipCreated = false;
        void CreateTooltip(int slot, UIElement[] children, Image imgItem)
        {
            itemTtp = new Controls.ItemTooltip(Character.Items[slot]);
            itemTtp.Replacing = children;
            pnlMid.Children.Clear();
            pnlMid.Children.Add(itemTtp);
            itemTtp.Height = 400;
            itemTtp.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            itemTtp.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            tooltipCreated = true;
            imgItem.Effect = CreateBlur(Colors.Yellow, 8, 2);
            blurredImage = imgItem;
        }

        private void imgItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            int slot = int.Parse((sender as Image).Tag.ToString());
            UIElement[] controlList;
            if (itemTtp == null)
            {
                controlList = new UIElement[pnlMid.Children.Count];
                pnlMid.Children.CopyTo(controlList, 0);
                CreateTooltip(slot, controlList, sender as Image);
            }
            else if (slot != itemTtp.Slot)
            {
                SetItemData(ref blurredImage, Character.Items[itemTtp.Slot], true);
                controlList = itemTtp.Replacing;
                CreateTooltip(slot, controlList, sender as Image);
                Image imgItem = sender as Image;
            }
            else
            {
                DisableItemTooltip();
            }
           
        }

        private void GlassWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!tooltipCreated) DisableItemTooltip();
            tooltipCreated = false;
        }
    }
}
